package com.jiamao.goplay.ui.photo.vm;

import android.app.Application;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.jiamao.goplay.BR;
import com.jiamao.goplay.R;
import com.jiamao.goplay.bean.BaseRep;
import com.jiamao.goplay.bean.res.ResAddrDetail;
import com.jiamao.goplay.bean.res.ResImage;
import com.jiamao.goplay.config.Config;
import com.jiamao.goplay.data.BaseSubscriber;
import com.jiamao.goplay.data.DataRepository;
import com.jiamao.goplay.ui.discover.SearchFragment;
import com.jiamao.goplay.ui.main.MainViewModel;
import com.tamsiree.rxkit.RxImageTool;
import com.tamsiree.rxkit.view.RxToast;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableArrayList;
import androidx.databinding.ObservableField;
import androidx.databinding.ObservableInt;
import androidx.databinding.ObservableList;

import org.reactivestreams.Subscriber;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.observers.DisposableObserver;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.base.MultiItemViewModel;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.bus.Messenger;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;
import me.goldze.mvvmhabit.utils.ImageUtils;
import me.goldze.mvvmhabit.utils.KLog;
import me.goldze.mvvmhabit.utils.RxUtils;
import me.tatarka.bindingcollectionadapter2.ItemBinding;
import me.tatarka.bindingcollectionadapter2.OnItemBind;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

public class PhotoUploadVM extends BaseViewModel<DataRepository> {

    public ObservableField<String> imgUrl = new ObservableField<>("");


    public int type = 0;

    public int from = 0 ;

    public ObservableInt errorUploadVisbility = new ObservableInt(View.GONE);
    public ObservableInt replepeUploadVisbility = new ObservableInt(View.GONE);

    public ObservableInt UploadIngVisbility = new ObservableInt(View.GONE);

    public PhotoUploadVM(@NonNull Application application, DataRepository repository) {
        super(application, repository);
        //模拟10个条目，数据源可以来自网络
    //    for (int i = 0; i < 20; i++) {

//             PhotoViewItmeVM item = new PhotoViewItmeVM(this);
//                observableList.add(item);

    //    }

    }



    //封装一个界面发生改变的观察者
    public UIChangeObservable uc = new UIChangeObservable();

    public class UIChangeObservable {
        //密码开关观察者
        public SingleLiveEvent<String> pSwitchEvent = new SingleLiveEvent<>();


    }



    //登录按钮的点击事件
    public BindingCommand backOnClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            finish();
        }
    });

    //条目的点击事件
    public BindingCommand  uploaddCommd = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            uploadImage();
        }
    });


    //条目的点击事件
    public BindingCommand  reuploaddCommd = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
           // startContainerActivity(SearchFragment.class.getCanonicalName());
            uploadImage();
        }
    });


    //条目的点击事件
    public BindingCommand  updatePhotodCommd = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            uc.pSwitchEvent.setValue("");
          //  startContainerActivity(SearchFragment.class.getCanonicalName());
        }
    });

    //给RecyclerView添加ObservableList
    public ObservableList<MultiItemViewModel> observableList = new ObservableArrayList<>();
    //RecyclerView多布局添加ItemBinding
    public ItemBinding<MultiItemViewModel> itemBinding = ItemBinding.of(new OnItemBind<MultiItemViewModel>() {
        @Override
        public void onItemBind(ItemBinding itemBinding, int position, MultiItemViewModel item) {
            //通过item的类型, 动态设置Item加载的布局
            String itemType = (String) item.getItemType();

            itemBinding.set(BR.viewModel, R.layout.photo_view_item_layout);

        }
    });




    public void uploadImage(){

      //  String filePath = "mnt/sdcard/1.png";

        if (TextUtils.isEmpty(imgUrl.get())){
            RxToast.error("图片不存在");
            return;
        }
       // try {

        KLog.d("压缩图片本地地址:" + imgUrl.get());


        try {
            ImageUtils.compressWithRx(imgUrl.get(), new Consumer<File>() {
                @Override
                public void accept(File o) throws Exception {
                    KLog.d("o:"+o.getPath());
                    uploadNet(o);
                }
            });

        }catch (Exception e){
            e.printStackTrace();
            RxToast.error("图片压缩失败");
            errorUploadVisbility.set(View.VISIBLE);
            replepeUploadVisbility.set(View.GONE);
            UploadIngVisbility.set(View.GONE);
        }

    }



    public void uploadNet(File file){

        //  String filePath = "mnt/sdcard/1.png";

        if (file == null){
            RxToast.error("图片不存在");
            return;
        }
        // try {
        // KLog.d("压缩图片本地地址:" + imgUrl.get());
//            ImageUtils.compressWithRx(imgUrl.get(), new Consumer<File>() {
//                @Override
//                public void accept(File file) throws Exception {


        //上传图片需要MultipartBody
        RequestBody requestBody = RequestBody.create(MediaType.parse("image/jpg"), file);
        MultipartBody.Part body = MultipartBody.Part.createFormData("File", file.getName(), requestBody);



        errorUploadVisbility.set(View.GONE);
        replepeUploadVisbility.set(View.GONE);
        UploadIngVisbility.set(View.GONE);

        RequestBody param = RequestBody.create(MediaType.parse("text/plain"), type + "");
        model.getApi().uploadImage(body, param)
                .compose(RxUtils.bindToLifecycle(getLifecycleProvider())) // 请求与View周期同步
                .compose(RxUtils.schedulersTransformer())  // 线程调度
                .compose(RxUtils.exceptionTransformer())   // 网络错误的异常转换
                .doOnSubscribe(this) //请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        //  showDialog();
                        UploadIngVisbility.set(View.VISIBLE);
                        // dialog.show();
                    }
                })
                .subscribe(new BaseSubscriber<BaseRep<ResImage>>() {

                    @Override
                    public void onError(Throwable throwable) {
                        //关闭对话框

                        throwable.printStackTrace();
                        //请求刷新完成收回
                        errorUploadVisbility.set(View.VISIBLE);
                        replepeUploadVisbility.set(View.GONE);
                        UploadIngVisbility.set(View.GONE);
                        // RxToast.showToastShort(throwable.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        //dismissDialog();
                        UploadIngVisbility.set(View.GONE);
                    }

                    @Override
                    public void onNext(BaseRep<ResImage> o) {
                        super.onNext(o);
                        dismissDialog();
                        Log.d("html", "aaaa " + o.getData().getPath());
                        Log.d("html", "aaaa " + o.getData().toString());

                        //   uc.image.setValue(o.getData().getPath());

                        if (o.isOk()) {
                            switch (from) {
                                case 0:
                                    Messenger.getDefault().send(o.getData().getPath(), Config.MGER_PHOTO_MAIN);
                                    break;
                                case 1:
                                    Messenger.getDefault().send(o.getData().getPath(), Config.MGER_PHOTO_LOGIN);
                                    break;
                                case 2:
                                    Messenger.getDefault().send(o.getData().getPath(), Config.MGER_PHOTO_EDIT);
                                    break;
                            }
                            finish();
                            // uc.image.setValue(o.getData().getPath());

                        } else {
                            UploadIngVisbility.set(View.GONE);
                            errorUploadVisbility.set(View.GONE);
                            replepeUploadVisbility.set(View.VISIBLE);

                            //  RxToast.showToastShort(o.getMsg());
                        }
                    }
                });



//
//        }catch (Exception e){
//            e.printStackTrace();
//            RxToast.error("图片压缩失败");
//            errorUploadVisbility.set(View.VISIBLE);
//            replepeUploadVisbility.set(View.GONE);
//            UploadIngVisbility.set(View.GONE);
//
//        }




    }



    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
